<template>
  <div class="lang-container">
    <van-popover v-model:show="showPopover" class="lang-popover">
      <div
        class="lang"
        v-for="(item, index) in langList"
        :key="index"
        :text="item.title"
        @click="changeActive(item.title)"
      >
        <div class="lang-item">
          <img :src="item.img" alt="" />
          <span>{{ item.desc }}</span>
        </div>
      </div>
      <template #reference>
        <img :src="getImageByTitle(active)" alt="" class="img" />
      </template>
    </van-popover>
  </div>
</template>
<script setup lang="ts">
import zhSvg from "@/assets/images/zh.svg";
import enSvg from "@/assets/images/en.svg";
import krSvg from "@/assets/images/kr.svg";
import jpSvg from "@/assets/images/jp.svg";
import thSvg from "@/assets/images/th.svg";
import vnSvg from "@/assets/images/vn.svg";
import { localStorage } from "@/utils/local-storage";
import { useI18n } from "vue-i18n";
const { locale } = useI18n();
const active = ref(locale.value || localStorage.get("lang"));
const langList = ref([
  {
    title: "zh",
    img: zhSvg,
    desc: "中文"
  },
  {
    title: "en",
    img: enSvg,
    desc: "English"
  },
  {
    title: "vi",
    img: vnSvg,
    desc: "Việt Nam"
  },
  {
    title: "th",
    img: thSvg,
    desc: "ประเทศไทย"
  },
  {
    title: "ja",
    img: jpSvg,
    desc: "日本語"
  },
  {
    title: "ko",
    img: krSvg,
    desc: "한국인"
  }
]);
const showPopover = ref(false);
const changeActive = lang => {
  locale.value = lang;
  active.value = lang;
  localStorage.set("lang", lang);
  showPopover.value = false;
};

const getImageByTitle = title => {
  const foundImage = langList.value.find(item => item.title === title);
  return foundImage ? foundImage.img : null;
};
</script>
<style scoped lang="scss">
.lang-container {
  display: flex;
  align-items: center;

  .img {
    height: 20px;
    border-radius: 2px;
  }
}

.lang-popover {
  background: #000508;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  .lang {
    display: flex;
    justify-content: center;
    padding: 10px;
    border-bottom: 1px solid #f1f1f1;
    .lang-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      img {
        height: 20px;
        margin-right: 20px;
      }
      span {
        font-size: 12px;
        font-weight: bold;
      }
    }
    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>
